const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');

const app = new Koa();
app.use(bodyParser());

const router = new Router();

// 文章列表
const getArticles = () => {
    const articles = [];
    for (let i = 1; i <= 100; i++) {
        articles.push({ id: i, title: `文章${i}`, content: `这是文章${i}的内容` })
    }
    return articles;
}
const articles = getArticles();

// 获取所有文章列表
router.get('/articles', (ctx, next) => {
    ctx.body = {
        code: 200,
        data: {
            articles
        },
        message: '获取文章列表成功'
    };
});

// 获取单篇文章
router.get('/articles/:id', async (ctx, next) => {
    await new Promise(resolve => setTimeout(resolve, Math.random() * 5000));
    const id = parseInt(ctx.params.id);
    const article = articles.find(a => a.id === id);
    if (article) {
        const random = Math.random();
        console.log('random', id, random);
        if (random > 0.5) {
            ctx.body = {
                code: 200,
                data: {
                    article
                },
                message: '获取文章成功'
            };
        } else {
            ctx.status = 500;
            ctx.body = {
                code: 500,
                data: null,
                message: '获取文章失败'
            };
        }
    } else {
        ctx.body = {
            code: 404,
            data: null,
            message: '文章不存在'
        };
    }
});

// 新增一篇文章
router.post('/articles', (ctx, next) => {
    const { title, content } = ctx.request.body;
    const id = articles.length + 1;
    articles.push({ id, title, content });
    ctx.body = {
        code: 200,
        data: {
            id
        },
        message: '新增文章成功'
    };
});

// 修改一篇文章
router.put('/articles/:id', (ctx, next) => {
    const id = parseInt(ctx.params.id);
    const article = articles.find(a => a.id === id);
    if (article) {
        const { title, content } = ctx.request.body;
        article.title = title;
        article.content = content;
        ctx.body = {
            code: 200,
            data: {
                article
            },
            message: '修改文章成功'
        };
    } else {
        ctx.body = {
            code: 404,
            data: null,
            message: '文章不存在'
        };
    }
});

// 删除一篇文章
router.delete('/articles/:id', (ctx, next) => {
    const id = parseInt(ctx.params.id);
    const index = articles.findIndex(a => a.id === id);
    if (index !== -1) {
        articles.splice(index, 1);
        ctx.body = {
            code: 200,
            data: null,
            message: '删除文章成功'
        };
    } else {
        ctx.body = {
            code: 404,
            data: null,
            message: '文章不存在'
        };
    }
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
    console.log('服务器已启动，监听端口3000');
});